﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Linq;


namespace P2.Cuberry.Framework.Helper
{
    public class P2Validator
    {
        public List<P2ValidationItemProperty> PropertyValidators = new List<P2ValidationItemProperty>();
        public List<P2ValidationItemUnique> UniqueValidators = new List<P2ValidationItemUnique>();
        public List<P2ValidationItemCompare> CompareValidators = new List<P2ValidationItemCompare>();

        private string _moduleID;
        private string _className;
        private string _keyName;
        public static IP2YellowPresenter YellowErrorDialog;

        #region "Cache"
        private static P2Validator _prevValidator = null;
        #endregion

        private P2Validator()
        {
        }
        public P2Validator(string ModuleID, string ClassName, string KeyName, object InitialObject)
        {
            _moduleID = ModuleID;
            _className = ClassName;
            _keyName = KeyName;
            this.FillMyObject(ModuleID, ClassName, KeyName, InitialObject);
        }


        protected void FillMyObject(string ModuleID, string ClassName, string KeyName, object InitialObject)
        {
            try
            {
                if (_prevValidator != null && _prevValidator._moduleID == ModuleID && _prevValidator._className == ClassName && _prevValidator._keyName == KeyName)
                {
                    this.PropertyValidators = _prevValidator.PropertyValidators.ToList();
                    this.UniqueValidators = _prevValidator.UniqueValidators.ToList();
                    this.CompareValidators = _prevValidator.CompareValidators.ToList();
                }
                else
                {
                    string connectionString = Configuration.ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResourcesValidation);
                    using (DAL.ValidationDataClassesDataContext db = new DAL.ValidationDataClassesDataContext(connectionString))
                    {
                        var contentRules = from fc in db.XConfigValidationFieldContent
                                           where fc.EntityName == this._className
                                           && fc.ModuleName == this._moduleID
                                           select fc;

                        var mandRules = from mr in db.XConfigValidationMandatoryFields
                                        where mr.EntityName == this._className
                                        select mr;
                        List<string> uniqueComb = new List<string>();
                        P2ValidationStatus uniqueCombValidationType = P2ValidationStatus.red;
                        foreach (var mandRule in mandRules)
                        {
                            P2ValidationStatus status;
                            if (string.IsNullOrEmpty(mandRule.ValidationType) || mandRule.ValidationType.ToLower() == "red")
                                status = P2ValidationStatus.red;
                            else
                                if (mandRule.ValidationType.ToLower() == "yellow")
                                    status = P2ValidationStatus.yellow;
                                else
                                    status = P2ValidationStatus.green;


                            if (mandRule.IsMandatory.GetValueOrDefault(false))
                            {
                                P2ValidationItemString strRule = new P2ValidationItemString()
                                {
                                    ClassName = this._className,
                                    ValidationType = status,
                                    Mandatory = true,
                                    PropertyName = mandRule.FieldName,
                                    MaxLength = int.MaxValue,
                                    MinLength = int.MinValue

                                };
                                PropertyValidators.Add(strRule);
                            }
                            if (mandRule.IsUnique.GetValueOrDefault(false))
                            {

                                P2ValidationItemUnique uniqueRule = new P2ValidationItemUnique()
                                {
                                    ClassName = this._className,
                                    KeyProperty = KeyName,
                                    ValidationType = status
                                };

                                uniqueRule.PropertyNames = new List<string>();
                                uniqueRule.PropertyNames.Add(mandRule.FieldName);
                                UniqueValidators.Add(uniqueRule);

                            }

                            if (mandRule.IsUniqueInCombination.GetValueOrDefault(false))
                            {
                                uniqueComb.Add(mandRule.FieldName);
                                uniqueCombValidationType = status;
                            }
                        }

                        if (uniqueComb.Count > 0)
                        {
                            P2ValidationItemUnique uniqueRule = new P2ValidationItemUnique()
                            {
                                ClassName = _className,
                                KeyProperty = KeyName,
                                ValidationType = uniqueCombValidationType,
                                PropertyNames = uniqueComb
                            };
                            UniqueValidators.Add(uniqueRule);
                        }

                        foreach (var rule in contentRules)
                        {
                            P2ValidationStatus status;
                            if (string.IsNullOrEmpty(rule.ValidationType) || rule.ValidationType.ToLower() == "red")
                                status = P2ValidationStatus.red;
                            else
                                if (rule.ValidationType.ToLower() == "yellow")
                                    status = P2ValidationStatus.yellow;
                                else
                                    status = P2ValidationStatus.green;

                            if (rule.ControlContentType == "Int32")
                            {

                                P2ValidationItemInteger intRule = new P2ValidationItemInteger()
                                {
                                    ClassName = this._className,
                                    PropertyName = rule.FieldName,
                                    ValidationType = status,
                                    MinValue = rule.MinInt.GetValueOrDefault(int.MinValue),
                                    MaxValue = rule.MaxInt.GetValueOrDefault(int.MaxValue)
                                };
                                PropertyValidators.Add(intRule);
                            }

                            if (rule.ControlContentType == "Text")
                            {

                                P2ValidationItemString strRule = new P2ValidationItemString()
                                {
                                    ClassName = this._className,
                                    PropertyName = rule.FieldName,
                                    ValidationType = status,
                                    MinLength = rule.MinText.GetValueOrDefault(int.MinValue),
                                    MaxLength = rule.MaxText.GetValueOrDefault(int.MaxValue),
                                    RegExTest = rule.RegEx
                                };
                                PropertyValidators.Add(strRule);
                            }

                            if (rule.ControlContentType == "Decimal")
                            {

                                P2ValidationItemDecimal strRule = new P2ValidationItemDecimal()
                                {
                                    ClassName = this._className,
                                    PropertyName = rule.FieldName,
                                    ValidationType = status,
                                    MinValue = rule.MinInt.GetValueOrDefault(int.MinValue),
                                    MaxValue = rule.MaxInt.GetValueOrDefault(int.MaxValue)

                                };
                                PropertyValidators.Add(strRule);
                            }

                            if (rule.ControlContentType == "DateTime")
                            {
                                P2ValidationItemDateTime strRule = new P2ValidationItemDateTime()
                                {
                                    ClassName = this._className,
                                    PropertyName = rule.FieldName,
                                    ValidationType = status,
                                    MinValue = rule.MinDateTime.GetValueOrDefault(DateTime.MinValue),
                                    MaxValue = rule.MaxDateTime.GetValueOrDefault(DateTime.MaxValue)

                                };
                                PropertyValidators.Add(strRule);
                            }
                        }

                    }
                    _prevValidator = new P2Validator();
                    _prevValidator._className = ClassName;
                    _prevValidator._keyName = KeyName;
                    _prevValidator._moduleID = ModuleID;
                    _prevValidator.PropertyValidators = PropertyValidators.ToList();
                    _prevValidator.UniqueValidators = UniqueValidators.ToList();
                    _prevValidator.CompareValidators = CompareValidators.ToList();
                }
                foreach (var valItem in PropertyValidators)
                {
                    valItem.StoreOriginalValues(InitialObject);
                }

                foreach (var valItem in UniqueValidators)
                {
                    valItem.StoreOriginalValues(InitialObject);
                }

                foreach (var valItem in CompareValidators)
                {
                    valItem.StoreOriginalValues(InitialObject);
                }

            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        public P2MessageStack Validate(object objectToValidate)
        {
            try
            {
                P2MessageStack messageStack = new P2MessageStack();
                foreach (var propertyValidator in PropertyValidators)
                {
                    messageStack.AddRange(propertyValidator.Validate(objectToValidate));
                }

                foreach (var compareValidator in CompareValidators)
                {
                    messageStack.AddRange(compareValidator.Validate(objectToValidate));
                }

                foreach (var uniqueValidator in UniqueValidators)
                {
                    messageStack.AddRange(uniqueValidator.Validate(objectToValidate));
                }
                return messageStack;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }


        public P2MessageStack ValidateProperty(object objectToValidate, string propertyToValidate)
        {
            try
            {
                P2MessageStack messageStack = new P2MessageStack();
                foreach (var propertyValidator in PropertyValidators)
                {
                    if (propertyValidator.PropertyName == propertyToValidate)
                        messageStack.AddRange(propertyValidator.Validate(objectToValidate));
                }
                foreach (var compareValidator in CompareValidators)
                {
                    if (compareValidator.PropertyName1 == propertyToValidate || compareValidator.PropertyName2 == propertyToValidate)
                        messageStack.AddRange(compareValidator.Validate(objectToValidate));
                }

                return messageStack;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }


    }
}
